from django.shortcuts import render
from apps.api.dataset.price_data import Price_Data
from apps.api.model.main import main
import numpy as np


# Create your views here.
def home(request):
    # 初始化数据表,返回一个表格字典。
    data = Price_Data().output()[['pub_time', 'weather_type', 'high_price', 'aver_price']].tail(50)
    # 将DataFrame转换为元组
    tuple_records = data.to_records(index=False)

    # lstm实例化
    config = r"apps/api/model/checkpoint/1/config.yaml"
    model = main(config, "prediction")
    plot_data, pub_time, residuals = model.predict()

    # 取白菜的三个值
    plot_data = plot_data[:, :, 0]
    # 真实值
    actual_data = np.round(plot_data[0], 2).tolist()
    # 训练值
    train_data = np.round(plot_data[1], 2).tolist()
    # 预测值
    pred_data = np.round(plot_data[2], 2).tolist()

    # 将数组中的NaN值替换为0
    actual_data = np.nan_to_num(actual_data, nan=0)
    train_data = np.nan_to_num(train_data, nan=0)
    pred_data = np.nan_to_num(pred_data, nan=0)

    # 返回记录数最高的四个产品
    max_four = Price_Data().max_count()

    # 构造响应s
    response = {
        'data': tuple_records,
        'actual_data': actual_data,
        'train_data': train_data,
        'pred_data': pred_data,
        'pub_time': pub_time.tolist(),
        'max_four': max_four,

        # 残差图数据
        'residuals': residuals
    }
    return render(request, 'index.html', response)


# 登录界面
def login(request):
    return render(request, 'login_register.html')
